<template>
    <div class="login-container">
        <el-card class="login-card">
            <template #header>
                <div class="card-header">
                    <span>xsap学校电子设备管理系统欢迎登录</span>
                </div>
            </template>
            <!-- 表单内容 -->
            <el-form :model="form" 
            label-position="left" 
            ref="ruleFormRef" 
            :rules="rules" 
            hide-required-asterisk>
                <el-form-item label="用户名" label-width="60px" prop="name">
                    <el-input v-model="form.name" placeholder="请输入用户名" :prefix-icon="User" />
                </el-form-item>
                <el-form-item label="密码" label-width="60px" prop="password">
                    <el-input v-model="form.password" placeholder="请输入密码" type="password" :prefix-icon="Lock" />
                </el-form-item>

                <!-- 验证码输入框 -->
                <el-form-item label="验证码" label-width="60px" prop="code">
                    <div class="captcha-container">
                        <el-input 
                            v-model="form.code" 
                            placeholder="请输入验证码" 
                            maxlength="4"
                            class="captcha-input"
                            @keyup.enter="handleLogin(ruleFormRef)"
                        />
                        <div class="captcha-image" @click="refreshCaptcha">
                            <canvas 
                                ref="captchaCanvas" 
                                width="120" 
                                height="40"
                                title="点击刷新验证码"
                            ></canvas>
                        </div>
                        <el-button 
                            size="small" 
                            @click="refreshCaptcha"
                            class="refresh-btn"
                        >
                            刷新
                        </el-button>
                    </div>
                </el-form-item>

                <!-- 登录和注册按钮 -->
                <el-form-item>
                    <div class="button-container">
                        <el-button type="primary" @click="handleLogin(ruleFormRef)" class="login-btn">
                            登录
                        </el-button>
                        <el-button type="success" @click="goToRegister" class="register-btn">
                            注册
                        </el-button>
                    </div>
                </el-form-item>

                <!-- 底部链接 -->
                <div class="footer-links">
                    <el-link type="primary" @click="goToRegister" :underline="false">
                        还没有账号？立即注册
                    </el-link>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()

//表单绑定的对象
const form = reactive({
    name: '',
    password: '',
    code: ''
})

//表单对象
const ruleFormRef = ref()
const captchaCanvas = ref()

// 验证码相关
const captchaCode = ref('')
const captchaChars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'

// 自定义验证码验证器
const validateCaptcha = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入验证码'))
    } else if (value.toLowerCase() !== captchaCode.value.toLowerCase()) {
        callback(new Error('验证码错误'))
    } else {
        callback()
    }
}

//表单验证
const rules = reactive({
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    code: [
        { required: true, validator: validateCaptcha, trigger: 'blur' }
    ]
})

// 生成随机验证码
const generateCaptcha = () => {
    let code = ''
    for (let i = 0; i < 4; i++) {
        code += captchaChars.charAt(Math.floor(Math.random() * captchaChars.length))
    }
    return code
}

// 绘制验证码
const drawCaptcha = () => {
    if (!captchaCanvas.value) return
    
    const canvas = captchaCanvas.value
    const ctx = canvas.getContext('2d')
    
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    
    // 设置背景
    const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)
    gradient.addColorStop(0, '#f0f2f5')
    gradient.addColorStop(1, '#e6e8eb')
    ctx.fillStyle = gradient
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    
    // 生成新的验证码
    captchaCode.value = generateCaptcha()
    
    // 绘制验证码文字
    const code = captchaCode.value
    ctx.textBaseline = 'middle'
    ctx.fillStyle = '#333'
    
    for (let i = 0; i < code.length; i++) {
        // 随机字体大小
        const fontSize = 16 + Math.random() * 8
        ctx.font = `${fontSize}px Arial`
        
        // 随机颜色
        const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD']
        ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)]
        
        // 随机位置和旋转
        const x = 15 + i * 25
        const y = canvas.height / 2 + (Math.random() - 0.5) * 8
        const angle = (Math.random() - 0.5) * 0.6
        
        ctx.save()
        ctx.translate(x, y)
        ctx.rotate(angle)
        ctx.fillText(code[i], 0, 0)
        ctx.restore()
    }
    
    // 添加干扰线
    for (let i = 0; i < 3; i++) {
        ctx.strokeStyle = `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.5)`
        ctx.lineWidth = 1
        ctx.beginPath()
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.stroke()
    }
    
    // 添加干扰点
    for (let i = 0; i < 30; i++) {
        ctx.fillStyle = `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.8)`
        ctx.beginPath()
        ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI)
        ctx.fill()
    }
}

// 刷新验证码
const refreshCaptcha = () => {
    drawCaptcha()
    form.code = '' // 清空输入框
    console.log('新验证码:', captchaCode.value) // 方便调试
}

// 跳转到注册页面
const goToRegister = () => {
    router.push('/register')
}

//登录的方法
const handleLogin = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) { // 基础验证通过
            console.log('提交登录信息:', form)
            
            try {
                // 调用后端登录接口
                const response = await axios.post('http://localhost:8080/api/v1/users/login', {
                    username: form.name,
                    password: form.password
                })

                console.log('登录响应:', response.data)

                if (response.data.code === 200) {
                    // 登录成功
                    ElMessage.success('登录成功')

                    // 中文角色转换为英文角色
                    const roleMapping = {
                        "系统管理员": "admin",
                        "设备管理员": "deviceAdmin",
                        "学生": "student",
                        "维修人员": "repairStaff"
                    }
                    const role = roleMapping[response.data.data.role] || "unknown"                    // 存储用户信息到 localStorage
                    localStorage.setItem('userId', response.data.data.userId)
                    localStorage.setItem('username', form.name)  // 存储用户名
                    localStorage.setItem('token', response.data.data.token)
                    localStorage.setItem('role', role) // 存储转换后的英文角色

                    // 设置全局请求头
                    axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.data.token}`

                    console.log('存储的用户信息:', {
                        userId: response.data.data.userId,
                        username: form.name,
                        role: role,
                        token: response.data.data.token
                    })

                    // 获取权限操作列表
                    try {
                        const operateRes = await axios.get(
                            `http://localhost:8080/api/v1/users/getRoleOperateList/${form.name}`,
                            {
                                headers: {
                                    'Authorization': `Bearer ${response.data.data.token}`
                                }
                            }
                        )
                        console.log('获取权限操作列表响应:', operateRes.data)
                        if (operateRes.data.code == "200") {
                            localStorage.setItem('operateList', JSON.stringify(operateRes.data))
                            // 跳转到仪表板
                            router.push('/dashboard')
                        }
                    } catch (e) {
                        console.error('获取权限操作列表失败:', e)
                        ElMessage.error('获取菜单权限失败')
                    }
                } else {
                    // 登录失败，刷新验证码
                    ElMessage.error(response.data.message || '登录失败')
                    refreshCaptcha()
                }
            } catch (error) {
                console.error('登录请求失败:', error)
                refreshCaptcha() // 失败时刷新验证码
                
                if (error.response) {
                    // 服务器返回错误状态码
                    ElMessage.error(error.response.data.message || '登录失败')
                } else if (error.request) {
                    // 网络错误
                    ElMessage.error('网络连接失败，请检查网络')
                } else {
                    // 其他错误
                    ElMessage.error('登录失败，请稍后重试')
                }
            }
        } else { // 基础验证不通过
            console.log('表单验证失败:', fields)
            // 如果验证码验证失败，刷新验证码
            if (fields.code) {
                refreshCaptcha()
            }
        }
    })
}

// 组件挂载后生成验证码
onMounted(() => {
    nextTick(() => {
        drawCaptcha()
    })
})
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-image: url("@/assets/img/loginbg-1.png");
    background-size: cover;
    background-position: center;
}

.login-card {
    width: 450px;
    padding: 10px;
}

.card-header {
    text-align: center;
    font-size: 24px;
}

.captcha-container {
    display: flex;
    align-items: center;
    gap: 10px;
}

.captcha-input {
    flex: 1;
}

.captcha-image {
    cursor: pointer;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
    transition: border-color 0.3s;
}

.captcha-image:hover {
    border-color: #409eff;
}

.captcha-image canvas {
    display: block;
    background: white;
}

.refresh-btn {
    white-space: nowrap;
}

/* 按钮容器样式 */
.button-container {
    display: flex;
    gap: 10px;
    width: 100%;
}

.login-btn,
.register-btn {
    flex: 1;
    height: 40px;
}

/* 底部链接样式 */
.footer-links {
    text-align: center;
    margin-top: 15px;
}

/* 响应式设计 */
@media (max-width: 480px) {
    .login-card {
        width: 90%;
        margin: 0 20px;
    }
    
    .captcha-container {
        flex-direction: column;
        align-items: stretch;
    }
    
    .captcha-image {
        align-self: center;
    }
    
    .button-container {
        flex-direction: column;
    }
    
    .login-btn,
    .register-btn {
        width: 100%;
    }
}
</style>